package com.gwsdk.paysdk.acitvityV2;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.gwsdk.open.GWApi;
import com.gwsdk.paysdk.acitvityV2.adapter.GWSmallAccountAdapter;
import com.gwsdk.paysdk.bean.LoginModel;
import com.gwsdk.paysdk.bean.PersonalCenterModel;
import com.gwsdk.paysdk.bean.SdkDomain;
import com.gwsdk.paysdk.callback.AddAccountCallback;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.dialog.AddAccountDialog;
import com.gwsdk.paysdk.dialog.GWTipDialog;
import com.gwsdk.paysdk.entity.UserLogin;
import com.gwsdk.paysdk.http.process.AddSmallAccountProgress;
import com.gwsdk.paysdk.http.process.SmallAccountLoginProgress;
import com.gwsdk.paysdk.utils.AppStatus;
import com.gwsdk.paysdk.utils.AppStatusManager;
import com.gwsdk.paysdk.utils.GWInflaterUtils;
import com.gwsdk.paysdk.utils.SharedPreferencesUtils;
import com.gwsdk.paysdk.utils.TextUtils;
import com.gwsdk.paysdk.utils.ToastUtil;
import com.gwsdk.paysdk.view.round.NiceImageView;
import com.lidroid.xutils.BitmapUtils;

import java.util.List;

public class GWChooseAccountActivity extends GWBaseActivity {

    private NiceImageView avatarImage;
    private TextView userName;
    private TextView switchAccount;
    private ListView smaleAccountListView;
    private UserLogin userLogin;
    private BitmapUtils bitmapUtils;
    private GWTipDialog mcTipDialog;
    private ImageView rememberImage;
    private List<UserLogin.SmallAccountEntity> smallAccountList;
    private TextView addAccount;
    private GWSmallAccountAdapter adapter;

    private Boolean isRemember = false;
    private Boolean isLogin = false;

    private AddAccountDialog.addAccountBuilder dialogBuilder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        bitmapUtils = new BitmapUtils(this);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏(主要功能就是去除页面弹出时顶部黑色条)
        if(AppStatusManager.getInstance().getAppStatus() == AppStatus.STATUS_RECYVLE){
            Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
            finish();
        }
        ComeOutType();
        super.onCreate(savedInstanceState);
        setContentView(GWInflaterUtils.getLayout(this,"gw_dialog_choose_account"));

        Bundle bundle = getIntent().getBundleExtra("bundle");

        this.userLogin = (UserLogin) bundle.getSerializable("userLogin");
        this.smallAccountList = userLogin.getSmallAccountList();

        initView();
    }

    private void initView(){

        avatarImage = findViewById(GWInflaterUtils.getControl(this,"avatar"));
        userName = findViewById(GWInflaterUtils.getControl(this,"user_name"));
        rememberImage = findViewById(GWInflaterUtils.getControl(this,"remember"));
        userName.setText(userLogin.getNickname());
        avatarImage.setCornerRadius(30);
        addAccount = findViewById(GWInflaterUtils.getControl(this,"add_account"));

        isRemember = SharedPreferencesUtils.getInstance().isRemember(this);

        rememberImage.setImageDrawable(getResources().getDrawable(isRemember
                ? GWInflaterUtils.getDrawable(this,"gw_selected_icon")
                : GWInflaterUtils.getDrawable(this,"gw_selected_no_icon")));

        if (userLogin.getUserIcon() != null && !userLogin.getUserIcon().isEmpty()){
            bitmapUtils.display(avatarImage,userLogin.getUserIcon());
        }else {
            if(!com.gwsdk.paysdk.utils.TextUtils.isEmpty(Constant.SDK_LOGO_URL)){
                bitmapUtils.display(avatarImage, Constant.SDK_LOGO_URL );
            }
        }

        findViewById(GWInflaterUtils.getControl(this,"switch_account")).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GWApi.getApi().isLogining = false;
                GWApi.getApi().loginout(GWChooseAccountActivity.this);
                finish();
            }
        });

        addAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (smallAccountList.size()>=10){
                    ToastUtil.show(GWChooseAccountActivity.this,"小号个数已满10，不可继续添加");
                }else {
                    dialogBuilder = new AddAccountDialog.addAccountBuilder().setSureClick(clickcallback);
                    dialogBuilder.show(GWChooseAccountActivity.this, getFragmentManager());
                }
            }
        });

        rememberImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isRemember = !isRemember;
                rememberImage.setImageDrawable(getResources().getDrawable(isRemember
                        ? GWInflaterUtils.getDrawable(GWChooseAccountActivity.this,"gw_selected_icon")
                        : GWInflaterUtils.getDrawable(GWChooseAccountActivity.this,"gw_selected_no_icon")));
                SharedPreferencesUtils.getInstance().setRemember(GWChooseAccountActivity.this,isRemember);
            }
        });

        smaleAccountListView = findViewById(GWInflaterUtils.getControl(this,"listView"));
        adapter = new GWSmallAccountAdapter(this);
        adapter.setLoginUser(userLogin);
        smaleAccountListView.setAdapter(adapter);
        smaleAccountListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isLogin == false){
                    isLogin = true;
                    smallAccountLogin(smallAccountList.get(position).getSmallUserId());
                }
            }
        });
        if (smallAccountList.size()>0){
            adapter.setListData(smallAccountList);

            boolean isRemember = SharedPreferencesUtils.getInstance().isRemember(this);
            if (isRemember) {
                String userId = SharedPreferencesUtils.getInstance().getLoginLastSmallAccount(this);
                for (UserLogin.SmallAccountEntity entity : smallAccountList) {
                    if (entity.getSmallUserId().equals(userId)){
                        if (isLogin == false){
                            isLogin = true;
                            smallAccountLogin(userId);
                        }
                        return;
                    }
                }
            }
        }
    }

    /**
     * 添加小号弹窗确认按钮点击事件
     */
    AddAccountCallback clickcallback = new AddAccountCallback() {
        @Override
        public void addAccount(String Account) {
            if (TextUtils.isEmpty(Account)){
                ToastUtil.show(GWChooseAccountActivity.this,"小号名不能为空");
                return;
            }
            dialogBuilder.closeDialog(getFragmentManager());
            mcTipDialog = new GWTipDialog.Builder().setMessage("请稍等...").show(GWChooseAccountActivity.this,getFragmentManager());
            AddSmallAccountProgress addSmallAccountProgress = new AddSmallAccountProgress();
            addSmallAccountProgress.setSmaleNickname(Account.trim());
            addSmallAccountProgress.setUserId(PersonalCenterModel.getInstance().getUserId());
            addSmallAccountProgress.setGameId(SdkDomain.getInstance().getGameId());
            addSmallAccountProgress.post(mHandler);
        }
    };

    private String loginSmallId = "";
    private void smallAccountLogin(String smallID){
        loginSmallId = smallID;
        SmallAccountLoginProgress progress = new SmallAccountLoginProgress();
        progress.setSmallUserId(smallID);
        progress.setUserId(userLogin.getAccountUserId());
        progress.setGameId(SdkDomain.getInstance().getGameId());
        progress.setYKLogin(userLogin.isYKLogin());
        progress.setToken(userLogin.getToken());
        progress.ageStatus = userLogin.getAgeStatus();
        progress.birthday = userLogin.getBirthday();
        progress.post(mHandler);
        mcTipDialog = new GWTipDialog.Builder().setMessage("进入游戏...").show(this,getFragmentManager());
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isLogin = false;
            if (null != mcTipDialog) {
                mcTipDialog.dismiss();
            }
            switch (msg.what) {
                case Constant.ADD_SMALL_ACCOUNT_SUCCESS:  //添加小号成功
                    UserLogin login = (UserLogin)msg.obj;
                    smallAccountList = login.getSmallAccountList();
                    adapter.setListData(smallAccountList);
                    ToastUtil.show(GWChooseAccountActivity.this, "添加成功");
                    break;
                case Constant.SMALL_ACCOUNT_LOGIN_SUCCESS:  //小号登录成功
                    UserLogin smallAccountLogin = (UserLogin) msg.obj;
                    LoginModel.instance().smallAccountLoginSuccess(smallAccountLogin);
                    if (isRemember){
                        SharedPreferencesUtils.getInstance().setLoginLastSmallAccount(GWChooseAccountActivity.this,loginSmallId);
                    }
                    SharedPreferencesUtils.getInstance().setLastLoginID(GWChooseAccountActivity.this,loginSmallId);
                    finish();
                    break;
                case Constant.SMALL_ACCOUNT_LOGIN_FAIL:  //小号登录失败
                    String tip = (String) msg.obj;
                    ToastUtil.show(GWChooseAccountActivity.this, tip);
                    LoginModel.instance().loginFail();
//                    btnPlay.setEnabled(true);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0,GWInflaterUtils.getIdByName(this,"anim","gw_scale_out"));//R.anim.gw_scale_out);
    }

    @Override
    public void onBackPressed() {

    }

    private void ComeOutType() {
        Window window = getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //透明状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        window.setDimAmount(0f); //设置背景透明度   0~1
        overridePendingTransition(GWInflaterUtils.getIdByName(this,"anim","gw_scale_in"),0);
    }



}
